# -*- coding: utf-8 -*-


import threading
import time
import paho.mqtt.client as mqtt

# mosquitto -v -c /etc/mosquitto/mosquitto.conf -d

host="39.96.40.177"
def on_message_sub(client, userdata, msg):
    res=str(msg.payload,encoding="utf-8")
    print(msg.topic + " sub " + res)
    if res=="wq9":
        pub_msg("topic","100")

def sub_msg(topic):
    client = mqtt.Client()
    client.on_message = on_message_sub
    client.connect(host, 1883, 600)
    client.subscribe(topic, qos=0)
    client.loop_forever()

def pub_msg(topic,msg):
    client = mqtt.Client()
    client.will_set(topic, 'Last will message', 0, False)
    client.connect(host, 1883, 600)
    client.publish(topic, payload=msg, qos=0)
    # 主动断开没有遗言
    # client.disconnect()

def main():
    # sub1=threading.Thread(target=sub_msg,args=("topic",))
    # sub1.start()
    for i in range(10):
        pub=threading.Thread(target=pub_msg,args=("topic","****"+str(i)))
        pub.start()

if __name__ == '__main__':
    main()



